/**
 * This is sample code provided by Wowza Media Systems, LLC.  All sample code is intended to be a reference for the
 * purpose of educating developers, and is not intended to be used in any production environment.
 * <p>
 * IN NO EVENT SHALL WOWZA MEDIA SYSTEMS, LLC BE LIABLE TO YOU OR ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
 * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
 * EVEN IF WOWZA MEDIA SYSTEMS, LLC HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * <p>
 * WOWZA MEDIA SYSTEMS, LLC SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ALL CODE PROVIDED HEREUNDER IS PROVIDED "AS IS".
 * WOWZA MEDIA SYSTEMS, LLC HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 * <p>
 * Copyright © 2015 Wowza Media Systems, LLC. All rights reserved.
 */

package com.zigong.app.ui.activities.wowza;

import android.Manifest;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.zigong.app.R;
import com.zigong.app.beans.LiveAdvanceInfo;
import com.zigong.app.ui.activities.wowza.widget.AutoFocusListener;
import com.zigong.app.ui.activities.wowza.widget.MultiStateButton;
import com.zigong.app.ui.activities.wowza.widget.TimerView;
import com.wowza.gocoder.sdk.api.devices.WZCamera;

/**
 * 直播拍摄页面
 */
public class CameraActivity extends CameraActivityBase {
    private final static String TAG = CameraActivity.class.getSimpleName();

    // UI controls
    protected MultiStateButton mBtnSwitchCamera = null;
    //    protected MultiStateButton      mBtnTorch         = null;
    protected TimerView mTimerView = null;

    // Gestures are used to toggle the focus modes
    protected GestureDetectorCompat mAutoFocusDetector = null;
    protected ImageView btnVolume;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        advanceInfo = (LiveAdvanceInfo) getIntent().getSerializableExtra("data");
        String key = getIntent().getStringExtra("key");
//        if (!TextUtils.isEmpty(key)) {
////            SDK_SAMPLE_APP_LICENSE_KEY = key;
//        }
        if (advanceInfo == null) {
            Toast.makeText(this, "直播配置信息错误，请联系管理员!", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stream_live);

        mRequiredPermissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
        };

        // Initialize the UI controls
//        mBtnTorch           = (MultiStateButton) findViewById(R.id.ic_torch);
        mBtnSwitchCamera = (MultiStateButton) findViewById(R.id.stream_top_switch);
        mTimerView = (TimerView) findViewById(R.id.txtTimer);
        findViewById(R.id.stream_top_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endBroadcast();
                finish();
            }
        });
        btnVolume = (ImageView) findViewById(R.id.stream_btn_volume);
        btnVolume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWZBroadcastConfig != null) {
                    mWZAudioDevice.setAudioEnabled(!isVoice);
                }
                if (mWZAudioDevice != null) {
                    mWZAudioDevice.setAudioPaused(!isVoice);

                }
                if (isVoice) {
                    btnVolume.setImageResource(R.mipmap.icon_player_volumned );
                } else {
                    btnVolume.setImageResource(R.mipmap.icon_player_mute);//TODO change pic
                }
                isVoice = !isVoice;
            }
        });
    }

    /**
     * Android Activity lifecycle methods
     */
    @Override
    protected void onResume() {
        super.onResume();

        if (this.hasDevicePermissionToAccess() && sGoCoderSDK != null && mWZCameraView != null) {
            if (mAutoFocusDetector == null)
                mAutoFocusDetector = new GestureDetectorCompat(this, new AutoFocusListener(this, mWZCameraView));

            WZCamera activeCamera = mWZCameraView.getCamera();
            if (activeCamera != null && activeCamera.hasCapability(WZCamera.FOCUS_MODE_CONTINUOUS))
                activeCamera.setFocusMode(WZCamera.FOCUS_MODE_CONTINUOUS);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * Click handler for the switch camera button
     */
    public void onSwitchCamera(View v) {
        if (mWZCameraView == null) return;

//        mBtnTorch.setState(false);
//        mBtnTorch.setEnabled(false);

        WZCamera newCamera = mWZCameraView.switchCamera();
        if (newCamera != null) {
            if (newCamera.hasCapability(WZCamera.FOCUS_MODE_CONTINUOUS))
                newCamera.setFocusMode(WZCamera.FOCUS_MODE_CONTINUOUS);

            boolean hasTorch = newCamera.hasCapability(WZCamera.TORCH);
//            if (hasTorch) {
//                mBtnTorch.setState(newCamera.isTorchOn());
//                mBtnTorch.setEnabled(true);
//            }
        }
    }

    /**
     * Click handler for the torch/flashlight button
     */
    public void onToggleTorch(View v) {
        if (mWZCameraView == null) return;

        WZCamera activeCamera = mWZCameraView.getCamera();
//        activeCamera.setTorchOn(mBtnTorch.toggleState());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mAutoFocusDetector != null)
            mAutoFocusDetector.onTouchEvent(event);

        return super.onTouchEvent(event);
    }

    /**
     * Update the state of the UI controls
     */
    @Override
    protected boolean syncUIControlState() {
        boolean disableControls = super.syncUIControlState();

        if (disableControls) {
            mBtnSwitchCamera.setEnabled(false);
//            mBtnTorch.setEnabled(false);
        } else {
            boolean isDisplayingVideo = (this.hasDevicePermissionToAccess(Manifest.permission.CAMERA) && getBroadcastConfig().isVideoEnabled() && mWZCameraView.getCameras().length > 0);
            boolean isStreaming = getBroadcast().getStatus().isRunning();

            if (isDisplayingVideo) {
                WZCamera activeCamera = mWZCameraView.getCamera();

//                boolean hasTorch = (activeCamera != null && activeCamera.hasCapability(WZCamera.TORCH));
//                mBtnTorch.setEnabled(hasTorch);
//                if (hasTorch) {
//                    mBtnTorch.setState(activeCamera.isTorchOn());
//                }

                mBtnSwitchCamera.setEnabled(mWZCameraView.getCameras().length > 0);
            } else {
                mBtnSwitchCamera.setEnabled(false);
//                mBtnTorch.setEnabled(false);
            }

            if (isStreaming && !mTimerView.isRunning()) {
                mTimerView.startTimer();
            } else if (getBroadcast().getStatus().isIdle() && mTimerView.isRunning()) {
                mTimerView.stopTimer();
            } else if (!isStreaming) {
                mTimerView.setVisibility(View.GONE);
            }
        }

        return disableControls;
    }
}
